package com.wj.rpsm.user.controller;

import com.wj.rpsm.user.pojo.vo.ResponsePojo;
import com.wj.rpsm.user.pojo.User;
import com.wj.rpsm.user.service.RoomService;
import com.wj.rpsm.user.service.UserService;
import com.wj.rpsm.user.utils.AliOSSUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * @author WeiJin
 * @version 1.0
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户相关api")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoomService roomService;


    /**
     * 登录
     *
     * @param account
     * @param password
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录，返回用户信息", notes = "明文登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", required = true, type = "String"),
            @ApiImplicitParam(name = "password", required = true, type = "String")
    })
    public ResponsePojo<User> login(@RequestParam("account") String account, @RequestParam("password") String password) {
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        User user = userService.login(account, password);
        if (Optional.ofNullable(user).isPresent()) {
            return ResponsePojo.success(user);
        }
        return ResponsePojo.fail(null, "登录失败");

    }


    /**
     * 根据id修改用户状态
     *
     * @param user
     * @return
     */
    @ApiOperation(value = "根据用户id修改状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userid", required = true, type = "Integer", paramType = "path"),
            @ApiImplicitParam(name = "user_status", required = true, type = "Integer", paramType = "query")
    })
    @PutMapping("/updateStatus/{userid}")
    public ResponsePojo<User> updateStatusById(@ApiIgnore User user) {
        int result = userService.updateStatusById(user);
        if (result == 0) {
            return ResponsePojo.fail(null, "该id失效");
        }
        return ResponsePojo.success(userService.getById(user.getUserid()));
    }

    /**
     * 获取用户信息
     *
     * @param id 用户Id
     * @return 返回是否成功
     */
    @ApiOperation("根据用户id获取信息，包含用户信息，房间信息")
    @ApiImplicitParam(name = "id", required = true, type = "Integer", paramType = "path")
    @GetMapping("getUserById/{id}")
    public ResponsePojo<User> getById(@PathVariable("id") Integer id) {
        User user = userService.getById(id);
        if (!Optional.ofNullable(user).isPresent()) {
            return ResponsePojo.fail(null, "该id不存在");
        }

        user.setRoom(roomService.getById((int) user.getUser_roomid()));
        return ResponsePojo.success(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user
     * @return
     */
    @ApiOperation(value = "根据id修改用户信息", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userid", type = "Integer", required = true),
            @ApiImplicitParam(name = "idcard", type = "String"),
            @ApiImplicitParam(name = "age", type = "Integer"),
            @ApiImplicitParam(name = "gender", type = "Integer"),
            @ApiImplicitParam(name = "username", type = "String"),
            @ApiImplicitParam(name = "password", type = "String"),
            @ApiImplicitParam(name = "user_status", type = "Integer"),
            @ApiImplicitParam(name = "account", type = "String")

    })
    @PutMapping("/update/byId")
    public ResponsePojo<User> updateUserById(@RequestBody @ApiIgnore User user) {

        if (Optional.ofNullable(userService.getUserByAccount(user.getAccount())).isPresent()) {
            return ResponsePojo.fail(null, "账号已存在");
        }
        Integer res = userService.updateInfo(user);
        if (res > 0) {
            return ResponsePojo.success(userService.getById(user.getUserid()));
        }
        return ResponsePojo.fail(null, "修改失败");
    }


    /**
     * 修改用户的头像
     *
     * @param file
     * @param id
     * @return
     */
    @PutMapping("/update/avatar")
    @ApiOperation(value = "修改头像", notes = "<span style='color:red'>仅支持.jpg/.jpeg/.png/.gif/.bmp格式的图片</span>")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "上传的文件", dataType = "_type",
                    dataTypeClass = MultipartFile.class, required = true),
            @ApiImplicitParam(name = "id", value = "修改谁的头像", dataType = "Integer", required = true)
    })
    public ResponsePojo<Map<String, String>> updateAvatar(@RequestPart MultipartFile file, @RequestParam("id") Integer id) {

        HashMap<String, String> map = new HashMap<>(0);
        String[] fileType = {"jpg", "jpeg", "png", "gif", "bmp"};
        //获取后缀名
        String name = file.getOriginalFilename();
        assert name != null : "获取文件名失败，为null";
        String[] names = name.split("\\.");
        String sufName = names[names.length - 1];
        //文件类型判断
        boolean exist = false;
        for (String type : fileType) {
            if (type.equals(sufName)) {
                exist = true;
                break;
            }
        }
        if (!exist) {
            map.put("message", "仅支持.jpg/.jpeg/.png/.gif/.bmp格式的图片");
            return ResponsePojo.fail(map, "不是常见图片类型");
        }
        //文件大小判断
        if (file.getSize() > 1024 * 50) {
            map.put("message", "文件大于50KB");
            return ResponsePojo.fail(map, "文件大于50KB");
        }
        //上传到阿里云OSS
        String fileName = null;
        try {
            fileName = new AliOSSUtil().upload(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (Objects.isNull(fileName)) {
            map.put("message", "上传失败");
            return ResponsePojo.fail(map, "上传失败");
        }
        //修改数据库地址
        User user = new User();
        user.setUserid(id);
        user.setUser_avatar(fileName);
        userService.updateInfo(user);
        map.put("url", fileName);
        return ResponsePojo.success(map);
    }
}
